// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 平滑滚动到指定区域
    window.scrollToSection = function(sectionId) {
        const section = document.getElementById(sectionId);
        if (section) {
            section.scrollIntoView({ behavior: 'smooth' });
        }
    };

    // 生成二维码
    generateQRCode();

    // 添加滚动监听，实现导航栏背景变化
    window.addEventListener('scroll', handleScroll);

    // 初始化页面动画
    initAnimations();
});

// 生成二维码
function generateQRCode() {
    const qrcodeContainer = document.getElementById('qrcode');
    if (qrcodeContainer) {
        // 清除之前的二维码
        qrcodeContainer.innerHTML = '';
        
        // 创建二维码
        new QRCode(qrcodeContainer, {
            text: window.location.href,
            width: 200,
            height: 200,
            colorDark: '#667eea',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    }
}

// 切换部门详情显示/隐藏
function toggleDepartment(card) {
    const isActive = card.classList.contains('active');
    
    // 关闭所有其他打开的部门卡片
    document.querySelectorAll('.department-card').forEach(dept => {
        dept.classList.remove('active');
    });
    
    // 如果点击的不是当前打开的卡片，则打开它
    if (!isActive) {
        card.classList.add('active');
    }
}

// 处理滚动事件
function handleScroll() {
    const navbar = document.querySelector('.navbar');
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    
    if (scrollTop > 50) {
        navbar.style.background = 'rgba(102, 126, 234, 0.95)';
        navbar.style.backdropFilter = 'blur(10px)';
    } else {
        navbar.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
        navbar.style.backdropFilter = 'none';
    }
}

// 初始化页面动画
function initAnimations() {
    // 创建观察器来检测元素是否进入视口
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
            }
        });
    }, observerOptions);

    // 观察所有需要动画的元素
    document.querySelectorAll('.department-card, .photo-card, .step').forEach(el => {
        observer.observe(el);
    });
}

// 添加CSS动画类
const style = document.createElement('style');
style.textContent = `
    .department-card, .photo-card, .step {
        opacity: 0;
        transform: translateY(30px);
        transition: opacity 0.6s ease-out, transform 0.6s ease-out;
    }
    
    .animate-in {
        opacity: 1 !important;
        transform: translateY(0) !important;
    }
    
    .department-card:nth-child(1) { transition-delay: 0.1s; }
    .department-card:nth-child(2) { transition-delay: 0.2s; }
    .department-card:nth-child(3) { transition-delay: 0.3s; }
    .department-card:nth-child(4) { transition-delay: 0.4s; }
    .department-card:nth-child(5) { transition-delay: 0.5s; }
    .department-card:nth-child(6) { transition-delay: 0.6s; }
`;
document.head.appendChild(style);

// 图片懒加载
function lazyLoadImages() {
    const images = document.querySelectorAll('img[data-src]');
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                observer.unobserve(img);
            }
        });
    });

    images.forEach(img => imageObserver.observe(img));
}

// 添加触摸支持
function addTouchSupport() {
    let touchStartY = 0;
    let touchEndY = 0;

    document.addEventListener('touchstart', e => {
        touchStartY = e.changedTouches[0].screenY;
    });

    document.addEventListener('touchend', e => {
        touchEndY = e.changedTouches[0].screenY;
        handleSwipe();
    });

    function handleSwipe() {
        const swipeThreshold = 50;
        const diff = touchStartY - touchEndY;
        
        if (Math.abs(diff) > swipeThreshold) {
            // 可以在这里添加滑动手势功能
        }
    }
}

// 添加键盘导航支持
function addKeyboardSupport() {
    document.addEventListener('keydown', e => {
        if (e.key === 'Tab') {
            // 确保焦点可见
            document.body.classList.add('keyboard-navigation');
        }
    });

    document.addEventListener('mousedown', () => {
        document.body.classList.remove('keyboard-navigation');
    });
}

// 初始化所有功能
document.addEventListener('DOMContentLoaded', () => {
    lazyLoadImages();
    addTouchSupport();
    addKeyboardSupport();
});

// 添加页面性能优化
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        // 可以在这里注册Service Worker进行缓存优化
    });
}

// 添加分享功能
function sharePage() {
    if (navigator.share) {
        navigator.share({
            title: '阳光志愿者社团 - 欢迎加入我们',
            text: '用爱心点亮世界，用行动传递温暖。加入我们，一起创造美好！',
            url: window.location.href
        });
    } else {
        // 复制链接到剪贴板
        navigator.clipboard.writeText(window.location.href).then(() => {
            alert('链接已复制到剪贴板！');
        });
    }
}

// 添加打印功能
function printPage() {
    window.print();
}

// 添加回到顶部按钮
function addBackToTopButton() {
    const backToTopButton = document.createElement('button');
    backToTopButton.innerHTML = '<i class="fas fa-arrow-up"></i>';
    backToTopButton.className = 'back-to-top';
    backToTopButton.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: #667eea;
        color: white;
        border: none;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        cursor: pointer;
        opacity: 0;
        transition: opacity 0.3s;
        z-index: 1000;
    `;
    
    document.body.appendChild(backToTopButton);
    
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 300) {
            backToTopButton.style.opacity = '1';
        } else {
            backToTopButton.style.opacity = '0';
        }
    });
    
    backToTopButton.addEventListener('click', () => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
}

// 初始化回到顶部按钮
document.addEventListener('DOMContentLoaded', addBackToTopButton);